<template>
  <div class="plan-analysis bg-background text-foreground p-4">
    <div class="bg-card text-card-foreground mb-4 rounded p-4 shadow">
      <div style="display: flex;align-items: baseline;">
        <span style="">日期时间 ：</span>
        <div style="margin-right:10px;display:flex;flex-direction: column;">
          <el-input type="date" v-model="fromtime.start_time" style="width: auto;" />
        </div>
        <div style="display:flex;flex-direction: column;">
          <el-input type="date" v-model="fromtime.end_time" style="width: auto;" />
        </div>
        <el-button type="primary" style="margin-left:10px" @click="searchPersonnel">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <!-- <query-form :model="search" :formItems="formItems" @search="searchPersonnel" @reset="resetSearch" /> -->
    </div>
    <div class="grid grid-cols-2 gap-4">
      <div class="bg-card rounded-lg p-4 shadow">
        <h2 class="text-xl font-bold mb-4">应急预案按类别统计</h2>
        <el-table v-loading="loading" :data="displayedPlanData" style="width: 100%" ref="table" align="center"
          class="data-table" :header-cell-style="headerCellStyle">
          <el-table-column prop="date_time" label="时间" header-align="center" align="center">

            <template #default="scope">
              {{ formatDateTimess(scope.row.date_time, 'date') }}
            </template>
          </el-table-column>
          <el-table-column prop="综合应急预案" label="综合应急预案" header-align="center" align="center"></el-table-column>
          <el-table-column prop="专项应急预案" label="专项应急预案" header-align="center" align="center"></el-table-column>
          <el-table-column prop="现场处置方案" label="现场处置方案" header-align="center" align="center"></el-table-column>
          <el-table-column prop="特殊时期/重大活动应急预案" label="特殊时期/重大活动应急预案" header-align="center"
            align="center"></el-table-column>
        </el-table>
        <Pagination v-if="result.length" :tableData="result" @alltabledata="alltabledata" />
      </div>


      <div class="bg-card rounded-lg p-4 shadow">
        <h2 class="text-xl font-bold mb-4">应急预案评估状态统计</h2>
        <pancake v-if="result22.length" :coundata="result22" xing="环状" title="环" />
      </div>


    </div>
    <div class="grid grid-cols-2 gap-4" style="margin-top:20px">
      <div class=" rounded-lg p-4 shadow">
        <h2 class="text-xl font-bold mb-4">应急预案统计</h2>
        <div>
          <el-button :type="time_granularity == 'year' ? 'primary' : ''" @click="searchtime('year')">年</el-button>
          <el-button :type="time_granularity == 'month' ? 'primary' : ''" @click="searchtime('month')">月</el-button>
        </div>
        <columnar v-if="timedata.total?.length" :coundata="timedata.total" title="应急" />
      </div>

      <div class=" rounded-lg p-4 shadow">
        <h2 class="text-xl font-bold mb-4">应急预案按等级统计</h2>
        <pancake v-if="timedata.type?.length" :coundata="timedata.type" title="应急" />
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, getCurrentInstance } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
import { dayjs } from "element-plus"
const { proxy } = getCurrentInstance()

const apiBaseUrl = ref(proxy.$currentUrl + '/api/plan-count')
import columnar from "../../components/echart/columnar.vue"
import brokenline from "../../components/echart/brokenline.vue"
import pancake from "../../components/echart/pancake.vue"
const displayedPlanData = ref([])
const alltabledata = (data) => {
  console.log(data)
  displayedPlanData.value = data

}
///////////////
// 用于存储整理后的数据
const result = ref([])
const result22 = ref([])
const keys = ["综合应急预案", "专项应急预案", "现场处置方案", "特殊时期/重大活动应急预案"]
const loading = ref(false)
const allRecords = ref([])
const timedata = ref([])
const pieChartContainer = ref(null)
const lineChartContainer = ref(null)
const statusChartContainer = ref(null)
let pieChart = null
let lineChart = null
let statusChart = null
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}

const fromtime = ref({
  start_time: new Date(),
  end_time: new Date()

})

const time_granularity = ref('year')
const resetSearch = () => {
  fromtime.value = {
    start_time: new Date(),
    end_time: new Date(),
  }
  // currentPage.value = 1;
  searchPersonnel()
}
const formatDateTimess = (dateTimeString, str) => {
  if (!dateTimeString) return null
  if (str != 'date') {
    const date = dayjs(dateTimeString).format('YYYY-MM-DD HH:mm:ss')
    return date
  } else {
    const date = dayjs(dateTimeString).format('YYYY-MM-DD')
    return date
  }

}




const searchPersonnel = async () => {
  result.value = []
  result22.value = []
  displayedPlanData.value = []
  fromtime.value.start_time = formatDateTimess(fromtime.value.start_time, 'date')
  fromtime.value.end_time = formatDateTimess(fromtime.value.end_time, 'date')
  try {
    // loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/countByCategory`, { params: fromtime.value })
    allRecords.value = response.data
    // loading.value = false
    allRecords.value.result_1.forEach(item => {
      const existing = result.value.find(r => r.date_time === item.date_time)
      if (existing) {
        for (const key of keys) {
          if (item[key] !== undefined) {
            existing[key] = item[key]
          }
        }
      } else {
        const newObj = { date_time: item.date_time }
        for (const key of keys) {
          newObj[key] = item[key] || 0
        }
        result.value.push(newObj)
      }
    })



    allRecords.value.result2.forEach(item => {
      const existingItem = result22.value.find(d => d.PLAN_REVIEWED_STATE === item.PLAN_REVIEWED_STATE)
      if (existingItem) {
        existingItem.Plan_Reviewed_State_Count += item.Plan_Reviewed_State_Count
      } else {
        result22.value.push({
          PLAN_REVIEWED_STATE: item.PLAN_REVIEWED_STATE,
          Plan_Reviewed_State_Count: item.Plan_Reviewed_State_Count
        })
      }
    })



    console.log(result22.value)

  } catch (error) {
    console.error('获取所有记录失败:', error)
    alert(
      '获取所有记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const searchtime = async (name) => {
  try {
    time_granularity.value = name
    const response = await axios.get(`${apiBaseUrl.value}/countGranularity`, {
      params: { time_granularity: time_granularity.value }
    })
    timedata.value = response.data
    console.log(timedata)
  } catch (error) {
    console.error('获取所有记录失败:', error)
    alert(
      '获取所有记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
onMounted(() => {
  searchPersonnel()
  searchtime('year')
  // await nextTick()

  // if (pieChartContainer.value) {
  //   pieChart = echarts.init(pieChartContainer.value)
  //   const pieOption = {
  //     title: {
  //       text: '应急预案修订状态统计',
  //       left: 'center'
  //     },
  //     tooltip: {
  //       trigger: 'item'
  //     },
  //     legend: {
  //       orient: 'vertical',
  //       left: 'right'
  //     },
  //     series: [
  //       {
  //         name: '修订状态',
  //         type: 'pie',
  //         radius: '50%',
  //         data: [
  //           { value: 3000, name: '已修订预案' },
  //           { value: 100, name: '未修订预案' }
  //         ],
  //         emphasis: {
  //           itemStyle: {
  //             shadowBlur: 10,
  //             shadowOffsetX: 0,
  //             shadowColor: 'rgba(0, 0, 0, 0.5)'
  //           }
  //         }
  //       }
  //     ]
  //   }
  //   pieChart.setOption(pieOption)
  // }

  // if (lineChartContainer.value) {
  //   lineChart = echarts.init(lineChartContainer.value)
  //   const lineOption = {
  //     title: {
  //       text: '应急预案类别趋势'
  //     },
  //     tooltip: {
  //       trigger: 'axis'
  //     },
  //     legend: {
  //       data: ['综合应急预案', '专项应急预案', '现场处置方案', '特殊时期/重大活动应急预案']
  //     },
  //     xAxis: {
  //       type: 'category',
  //       data: ['2401', '2402', '2403', '2404', '2405', '2406']
  //     },
  //     yAxis: {
  //       type: 'value'
  //     },
  //     series: [
  //       {
  //         name: '综合应急预案',
  //         type: 'line',
  //         data: [50, 60, 55, 58, 70, 68]
  //       },
  //       {
  //         name: '专项应急预案',
  //         type: 'line',
  //         data: [40, 45, 42, 48, 55, 52]
  //       },
  //       {
  //         name: '现场处置方案',
  //         type: 'line',
  //         data: [30, 35, 32, 38, 45, 42]
  //       },
  //       {
  //         name: '特殊时期/重大活动应急预案',
  //         type: 'line',
  //         data: [20, 25, 22, 28, 35, 32]
  //       }
  //     ]
  //   }
  //   lineChart.setOption(lineOption)
  // }

  // if (statusChartContainer.value) {
  //   statusChart = echarts.init(statusChartContainer.value)
  //   const statusOption = {
  //     title: {
  //       text: '应急预案状态趋势'
  //     },
  //     tooltip: {
  //       trigger: 'axis'
  //     },
  //     legend: {
  //       data: ['未修订预案', '已修订预案']
  //     },
  //     xAxis: {
  //       type: 'category',
  //       data: ['2401', '2402', '2403', '2404', '2405', '2406']
  //     },
  //     yAxis: {
  //       type: 'value'
  //     },
  //     series: [
  //       {
  //         name: '未修订预案',
  //         type: 'line',
  //         data: [20, 22, 21, 23, 25, 24]
  //       },
  //       {
  //         name: '已修订预案',
  //         type: 'line',
  //         data: [50, 55, 53, 58, 65, 63]
  //       }
  //     ]
  //   }
  //   statusChart.setOption(statusOption)
  // }
})

// window.addEventListener('resize', () => {
//   if (pieChart) pieChart.resize()
//   if (lineChart) lineChart.resize()
//   if (statusChart) statusChart.resize()
// })







</script>

<style scoped>
/* 移除大部分样式，因为现在由 Tailwind 类处理 */
.btn {
  @apply rounded-md px-4 py-2 font-medium transition duration-150 ease-in-out focus:outline-none focus:ring-2 focus:ring-offset-2;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

:deep(.dialog-from .el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}

.box-title {
  margin-bottom: 10px;
}

:deep(.box-color) {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}

.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}


.input-time-query {
  margin-top: 0;
  border-radius: 5%;
  display: inline-block;
  box-shadow: 0 0 0 1px #dcdfe6;
  width: 180px;
  height: 32px;
}

.input-time-query:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}
</style>
